In [4]:
from collections import Counter

In [5]:
Counter('with a string')


Out[5]:
Counter({' ': 2,
         'a': 1,
         'g': 1,
         'h': 1,
         'i': 2,
         'n': 1,
         'r': 1,
         's': 1,
         't': 2,
         'w': 1})

In [6]:
Counter('with a string'.split())


Out[6]:
Counter({'a': 1, 'string': 1, 'with': 1})

In [28]:
c = Counter([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 5, 6, 100, 'test'])

In [9]:
c


Out[9]:
Counter({1: 3, 2: 2, 3: 8, 5: 1, 6: 1, 100: 1, 'test': 1})

In [12]:
c.viewitems()


Out[12]:
dict_items([(1, 3), (2, 2), (3, 8), (100, 1), (5, 1), (6, 1), ('test', 1)])

In [19]:
for k, v in c.iteritems(): 
    print "key:", k, "value:", v


key: 1 value: 3
key: 2 value: 2
key: 3 value: 8
key: 100 value: 1
key: 5 value: 1
key: 6 value: 1
key: test value: 1

In [21]:
c.most_common() # descending order of most common


Out[21]:
[(3, 8), (1, 3), (2, 2), (100, 1), (5, 1), (6, 1), ('test', 1)]

In [22]:
c.most_common(1)


Out[22]:
[(3, 8)]

In [23]:
c.most_common(3)


Out[23]:
[(3, 8), (1, 3), (2, 2)]

In [34]:
c


Out[34]:
Counter({1: 3, 2: 2, 3: 8, 5: 1, 6: 1, 100: 1, 'test': 1})

In [30]:
list(c)


Out[30]:
[1, 2, 3, 100, 5, 6, 'test']

In [31]:
set(c)


Out[31]:
{1, 2, 3, 5, 6, 100, 'test'}

In [32]:
dict(c)


Out[32]:
{1: 3, 2: 2, 3: 8, 5: 1, 6: 1, 100: 1, 'test': 1}

In [39]:
c.most_common()[:-4-1:-1]


Out[39]:
[('test', 1), (6, 1), (5, 1), (100, 1)]

defaultdict

The whole point is that it will always return a value even if you query for a key that doesnt exist. That value you set ahead of time is called a factory object. That key also gets turned into a new key/value pair with the factory object


In [41]:
from collections import defaultdict

In [42]:
d = {'k1':1}

In [43]:
d["k1"]


Out[43]:
1

In [44]:
d["k2"] # this will get an error because the k2 key doesnt exist


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-44-d5a5b2fb6795> in <module>()
----> 1 d["k2"]

KeyError: 'k2'

In [45]:
d = defaultdict(object)

In [46]:
d['one'] # this doesn't exist, but in calling for it it will create a new element {'one' : object}


Out[46]:
<object at 0x1023693f0>

In [48]:
d['two'] # same, this will add {'two' : object}


Out[48]:
<object at 0x102369410>

In [50]:
for k, v in d.items():
    print "key:", k, "item:", v


key: two item: <object object at 0x102369410>
key: one item: <object object at 0x1023693f0>

In [59]:
e = defaultdict(lambda: 0) # lambda just returns 0 here

In [61]:
e['four']
e['twelve']


Out[61]:
0

In [64]:
def error():
    return 'error'

f = defaultdict(error) #returned item must be callable or None

In [65]:
f['new']


Out[65]:
'error'

In [66]:
f.items()


Out[66]:
[('new', 'error')]

orderedDict

dictionary subclass that remembers the order items were added


In [70]:
d_norm = {}
d_norm['a'] = 1
d_norm['b'] = 2
d_norm['c'] = 3
d_norm['d'] = 4
d_norm['e'] = 5

# order isn't preserved since a dict is just a mapping
for k,v in d_norm.items():
    print k,v


a 1
c 3
b 2
e 5
d 4

In [73]:
from collections import OrderedDict

In [77]:
d_ordered = OrderedDict()
d_ordered['a'] = 1
d_ordered['b'] = 2
d_ordered['c'] = 3
d_ordered['d'] = 4
d_ordered['e'] = 5

In [78]:
for k,v in d_ordered.items():
    print k, v


a 1
b 2
c 3
d 4
e 5

In [79]:
from collections import namedtuple

In [81]:
# this is kind of like creating a new class on the fly
# the first parameter of a namedtuple is the name of the class/tuple type
# the second parameter is a space-delimeted list of properties of the tuple
Dog = namedtuple('Dog','age breed name')
sam = Dog(age=2, breed='Lab', name='Sammy')

In [82]:
print sam.age
print sam.breed
print sam.name


2
Lab
Sammy

In [102]:
Catzz = namedtuple('Cat', 'fur claws name')
mittens = Catzz(fur='fuzzy', claws='sharp', name='Mittens')
print type(mittens)
print type(Catzz)
print mittens[0]
print mittens.claws
print mittens.name
print mittens.count('fuzzy')
print mittens.index('sharp')


<class '__main__.Cat'>
<type 'type'>
fuzzy
sharp
Mittens
1
1

In [ ]: